#include "wind_speed.h"

// 计算 Modbus CRC16
static uint16_t modbus_crc16(const uint8_t *data, uint16_t len)
{
    uint16_t crc = 0xFFFF;
    for (uint16_t i = 0; i < len; i++)
    {
        crc ^= data[i];
        for (int j = 0; j < 8; j++)
        {
            if (crc & 0x0001)
                crc = (crc >> 1) ^ 0xA001;
            else
                crc >>= 1;
        }
    }
    return crc;
}

// 假设这里可以根据风速值返回描述，比如风速等级描述，这里简单返回空字符串示例
static const char *GetWindSpeedDescription(float speed)
{
    return "";
}

// 读取一次风速数据的函数
static float read_wind_speed_data()
{
    uint8_t tx_buf[8] = {0};
    uint8_t rx_buf[16] = {0};

    tx_buf[0] = MODBUS_ADDR;
    tx_buf[1] = MODBUS_FUNC_READ;
    tx_buf[2] = (WIND_SPEED_REG_ADDR >> 8) & 0xFF;
    tx_buf[3] = WIND_SPEED_REG_ADDR & 0xFF;
    tx_buf[4] = (WIND_SPEED_REG_COUNT >> 8) & 0xFF;
    tx_buf[5] = WIND_SPEED_REG_COUNT & 0xFF;

    uint16_t crc = modbus_crc16(tx_buf, 6);
    tx_buf[6] = crc & 0xFF;        // CRC低位
    tx_buf[7] = (crc >> 8) & 0xFF; // CRC高位

    int ret = IoTUartWrite(WIND_SPEED_UART_ID, tx_buf, 8);
    if (ret <= 0)
    {
        printf("[WIND_SPEED] UART write failed\n");
        return;
    }

    usleep(100000); // 延迟等待数据返回

    ret = IoTUartRead(WIND_SPEED_UART_ID, rx_buf, sizeof(rx_buf));
    if (ret < 7)
    {
        printf("[WIND_SPEED] UART read failed or not enough data (ret=%d)\n", ret);
        return;
    }

    printf("[WIND_SPEED] Received %d bytes:\n", ret);
    for (int i = 0; i < ret; i++)
    {
        printf("%02X ", rx_buf[i]);
    }
    printf("\n");

    if (rx_buf[0] != MODBUS_ADDR || rx_buf[1] != MODBUS_FUNC_READ || rx_buf[2] != 0X04)
    {
        printf("[WIND_SPEED] Invalid response header\n");
        return;
    }

    uint16_t wind_speed_val = (rx_buf[3] << 8) | rx_buf[4];
    float wind_speed = wind_speed_val * 0.1f; // 假设风速值转换关系，实际按硬件情况调整

    const char *wind_speed_desc = GetWindSpeedDescription(wind_speed);
//    printf("[WIND_SPEED] Speed: %.1f m/s (%s)\n", wind_speed, wind_speed_desc);
	return wind_speed;
}

// 风速数据读取任务，包含循环逻辑
static float wind_speed_task(void *arg)
{
    IoTUartDeinit(WIND_SPEED_UART_ID); // 防止占用，重新初始化

    IotUartAttribute attr = {
        .baudRate = WIND_SPEED_UART_BAUDRATE,
        .dataBits = IOT_UART_DATA_BIT_8,
        .parity = IOT_UART_PARITY_NONE,
        .stopBits = IOT_UART_STOP_BIT_1,
        .rxBlock = IOT_UART_BLOCK_STATE_BLOCK,
        .txBlock = IOT_UART_BLOCK_STATE_BLOCK,
        .pad = IOT_FLOW_CTRL_NONE,
    };

    if (IoTUartInit(WIND_SPEED_UART_ID, &attr) != IOT_SUCCESS)
    {
        printf("[WIND_SPEED] Failed to init UART%d\n", WIND_SPEED_UART_ID);
        return;
    }

    while (1)
    {
        read_wind_speed_data();
        usleep(2000000); // 每2秒读取一次
    }
}

// 初始化风速任务
void wind_speed_init(void)
{
    TSK_INIT_PARAM_S task = {
        .pfnTaskEntry = (TSK_ENTRY_FUNC)wind_speed_task,
        .uwStackSize = WIND_SPEED_TASK_STACK,
        .pcName = "wind_speed",
        .usTaskPrio = WIND_SPEED_TASK_PRIO,
    };
    unsigned int tid;
    if (LOS_TaskCreate(&tid, &task) != LOS_OK)
    {
        printf("[WIND_SPEED] Failed to create wind speed task\n");
    }
}
